<template>
  <MenuPage 
    :columns="columns" 
    :data="datasource"
    :page.sync="queryObj.pageIndex"
    :size.sync="queryObj.pageSize"
    :total="total"
    :loading="loading"
    @queryFun="queryList">
    <template slot="search">
        <Button type="primary" ghost @click="addItem($event, 'add')" class="md-add-jh"
          >创建技能树</Button
        >
        <Divider type="vertical" />
        <Checkbox v-model="queryObj.isMe" class="gap" @on-change="isCreatByMe()">由我创建</Checkbox>
        <Select filterable
          placeholder="可用状态"
          class="gap select"
          v-model="queryObj.available"
          @on-change="queryList"
        >
          <Option :value="-1">全部</Option>
          <Option :value="0">不可用</Option>
          <Option :value="1">可用</Option>
        </Select>
        <Input
          v-model.trim="queryObj.name"
          class="gap input"
          clearable
          placeholder="技能树名称"
          @on-change="queryListD"
        />
        <Button type="primary" ghost class="gap button" @click="queryList('refresh')"
          ><i class="el-icon-refresh-right"
        /></Button>
    </template>
    <AddModal ref="addmodal" @refreshList="queryList"></AddModal>
    <show-tree-detail ref="treeDetail"></show-tree-detail>
    <Modal v-model="collectModal" title="收藏人数详细信息" :footer-hide="true" :width="700">
      <TableList 
        :columns="collectSkillCol" 
        :data="collectSkillData"  
        :size.sync="collectSkillObj.pageSize"
        :page.sync="collectSkillObj.pageIndex"
        :total="collectSkillTotal"
        @queryFun="getCollectSkillData"
        >
      </TableList>
    </Modal>
  </MenuPage>
</template>
<script>
import { setDefaultHeight, handlerAvailable } from './skillCommon';
import $ from 'jquery';
import usally from '@/mixin/usally';
import encryption from '@/libs/encryption.js';
import { querySkill, modifySkill, delSkill, getCollectSkillPeople } from '@/api/selfStudy/skill.js';
import AddModal from './addModal.vue';
// import { Progress, Switch } from 'view-design';
import { throttle, debounce } from '@/libs/utils';
import ShowTreeDetail from './showTreeDetail.vue';
import pageTitle from '@/mixin/pageTitle';
export default {
  name: 'solutionPage',
  components: { AddModal, ShowTreeDetail},
  mixins: [usally,pageTitle],
  data() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    let _this = this;
    return {
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      defaultPagesize: setDefaultHeight(),
      //收藏人数详情
      collectModal: false,
      currentCollectSkill: '',
      currentCollectId: '',
      collectSkillData: [],
      collectSkillTotal: 0,
      collectSkillObj: {
        pageIndex: 1,
        pageSize: 12
      },
      collectSkillCol: [
        {
          title: '昵称',
          key: 'showName',
          tooltip: true
        },
        {
          title: '状态',
          key: 'state',
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color: params.row.state == 1 ? 'green' : 'red'
                }
              },
              params.row.state == 1 ? '已完成' : '未完成'
            );
          }
        },
        {
          title: '完成进度',
          key: 'progress',
          render: (h, params) => {
            return h('Progress', {
              props: {
                percent: params.row.progress.replace('%', '') * 1
              }
            });
          }
        },
        {
          title: '收藏时间',
          key: 'createTime'
        }
      ],
      //列表查询对象
      queryObj: {
        pageIndex: 1,
        pageSize: this.defaultPagesize,
        name: '',
        available: -1,
        isMe: false
      },
      currentObj: {},
      columns1: [
        {
          type:'link',
          title: '技能树名称',
          key: 'name',
          align: 'center',
          placement: 'top-left',
          width: 100,
          minWidth:100,
          on:{
            click:(data) => {
              this.$router.push({
                name: 'skillTreeDetail',
                query: {
                  name:data.name,
                  id: data.id
                }
              });
            }
          }
        },
        {
          title: '描述',
          key: 'description',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 250,
          minWidth:50,
        },
        {
          title: '状态', //0 否，1是
          key: 'available',
          placement: 'top-right',
          minWidth:50,
          render: (h, params) => {
            return h(
              'Tag',
              {
                style: {
                  width: '60px',
                  'text-align-last': 'justify'
                },
                props: {
                  color: handlerAvailable(params.row.available).color
                }
              },
              handlerAvailable(params.row.available).txt
            );
          }
        },
        {
          title: '收藏人数', //0 否，1是
          key: 'collectCount',
          placement: 'top-right',
          minWidth:50,
          render: (h, params) => {
            return h(
              'Tag',
              {
                style: {
                  'text-align-last': 'justify',
                  cursor: 'pointer!important'
                },
                props: {
                  color: 'blue'
                },
                nativeOn: {
                  click: () => {
                    if (params.row.collectCount == 0) {
                      this.$Message.info('当前无人收藏该技能树');
                      return;
                    }
                    this.openCollectModal(params.row.id, params.row.name);
                  }
                }
              },
              params.row.collectCount
            );
          }
        },
        // {
        //     title:'检测结果',
        //     key:'checkResult',
        //     width:200,
        //     render:(h,params)=>{
        //         return h('Tooltip',{
        //             props:{
        //                 placement: 'top-start',
        //                 transfer: true,
        //                 maxWidth:200,
        //                 content:(!params.row.available)&&params.row.checkResult?params.row.checkResult:'-'
        //             },
        //             style:{
        //                 width:'100%'
        //             }
        //         },[
        //             h('span',{
        //                 style:{
        //                 'white-space': 'nowrap',
        //                 'text-overflow': 'ellipsis',
        //                 'overflow': 'hidden',
        //                 'width': '100%'
        //                 }
        //             },(!params.row.available)&&params.row.checkResult?params.row.checkResult:'-')
        //         ])
        //     }
        // },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'center',
          tooltip: true,
          width: 100,
          minWidth:50,
        },
        {
          title: '创建时间',
          key: 'createTime',
          minWidth:50,
        },
        {
          title: '操作',
          placement: 'top-right',
          action:true,
          width:60,
          render: (h, params) => {
            return h('div', {}, [
              h(
                'i-switch',
                {
                  props: {
                    size: 'large',
                    value: params.row.available ? true : false,
                    disabled:
                      (!this.isRootDesigner && params.row.creator != this.USER_ID) ||
                      params.row.collect,
                    'before-change': (val) => {
                      if (
                        (!this.isRootDesigner && params.row.creator != this.USER_ID) ||
                        params.row.collect
                      ) {
                        return;
                      }
                      return new Promise((resolve) => {
                        let passObj = { ...params.row };
                        passObj.available = passObj.available ? 0 : 1;
                        const txt = passObj.available ? '开启' : '关闭';
                        modifySkill(passObj)
                          .then((res) => {
                            if (res.code == 1) {
                              this.$Message.info(txt + '完成');
                              this.queryList();
                              resolve();
                            } else {
                              this.$Message.error(res.message);
                            }
                          })
                          .catch((error) => {});
                      });
                    }
                  },
                  class: {
                    skillTree: true
                  },
                  style: {
                    'margin-right': '10px',
                    'margin-top': '-5px',
                    display: 'inline-block'
                    // width:'75px',
                    // height:'29px',
                    // 'line-height':'29ppx'
                  },
                  attrs: {
                    id: `switch-${params.row.id}`,
                    title:
                      '开启/关闭技能树可用状态,技能树所有节点间都创建了连线并且绑定了训练内容才可开启技能树'
                  },
                  on: {
                    'before-change': (val) => {
                      ;
                      return new Promise((resolve) => {
                        this.$Modal.confirm({
                          title: '切换确认',
                          content: '您确认要切换开关状态吗？',
                          onOk: () => {
                            resolve();
                          }
                        });
                      });
                      return;
                      if (
                        (!this.isRootDesigner && params.row.creator != this.USER_ID) ||
                        params.row.collect
                      ) {
                        return;
                      }
                      let passObj = { ...params.row };
                      passObj.available = passObj.available ? 0 : 1;
                      const txt = passObj.available ? '开启' : '关闭';
                      modifySkill(passObj)
                        .then((res) => {
                          if (res.code == 1) {
                            this.$Message.info(txt + '完成');
                            this.queryList();
                          } else {
                            // 没找到什么办法
                            this.datasource[params.index].available = 0;
                            let switchEl = document.getElementById(`switch-${params.row.id}`);
                            switchEl.className = 'ivu-switch  ivu-switch-large skillTree';
                            switchEl.innerHTML = `<input type="hidden" value="false"> <span class="ivu-switch-inner"><!----> <span data-v-66f9a28c="">关闭</span></span>`;
                            this.$Message.error(res.message);
                          }
                        })
                        .catch((error) => {});
                    }
                  },
                  nativeOn: {
                    click: () => {}
                  }
                },
                [h('span', { slot: 'open' }, '开启'), h('span', { slot: 'close' }, '关闭')]
              ),
              // h('i-switch',{
              // props:{
              //     size:'large',
              //     value: params.row.matchType?true:false,
              //     disabled: (!this.isRootDesigner)&&(params.row.creator!=this.USER_ID)
              // },
              // class:{
              //     'skillTree':true
              // },
              // style:{
              //     'margin-right':'10px',
              //     'margin-top': '-5px',
              //     display: 'inline-block'
              // },
              // attrs:{
              //     title:'开启/关闭按难易级别学习方式'
              // },
              // on:{
              //     'on-change':(val)=>{
              //         params.row.currentMatchType = val;
              //     }
              // },
              // nativeOn: {
              //     click: () => {
              //         if((!this.isRootDesigner)&&(params.row.creator!=this.USER_ID)){
              //             return;
              //         }
              //         console.log(params.row.currentMatchType)
              //         let passObj = {...params.row};
              //         passObj.matchType = params.row.currentMatchType?1:0;
              //         const txt=params.row.currentMatchType?'开启':'关闭'
              //         modifySkill(passObj).then(res=>{
              //             if(res.code==1){
              //                 this.$Message.info(txt+'完成');
              //                 this.queryList()
              //             }else{
              //                 this.$Message.error(res.message);
              //             }
              //         })
              //     },
              // },
              // },[
              //     h('span', { slot: 'open' }, '开启'),
              //     h('span', { slot: 'close' }, '关闭'),
              // ]),
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  attrs: {
                    title: '预览'
                  },
                  style: {
                    background: 'none',
                    border: 'none',
                    boxShadow: 'none'
                  },
                  on: {
                    click: () => {
                      this.showItem(params);
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src: require('@/assets/project/magnifier-h.png')
                    },
                    style: {
                      cursor: 'pointer',
                      'margin-right': '5px',
                      'vertical-align': 'middle',
                      display: 'inline-block',
                      marginBottom: '4px'
                    }
                  })
                ]
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small',
                    disabled:
                      (!this.isRootDesigner && params.row.creator != this.USER_ID) ||
                      params.row.collect
                  },
                  attrs: {
                    title: '修改'
                  },
                  style: {
                    background: 'none',
                    border: 'none',
                    boxShadow: 'none'
                  },
                  on: {
                    click: () => {
                      // if (params.row.available) {
                      //     console.log('修改前请先关闭技能树');
                      //     return;
                      // }
                      this.$refs.addmodal.open(params.row);
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src:
                        (!this.isRootDesigner && params.row.creator != this.USER_ID) ||
                        params.row.collect
                          ? require('@/assets/project/modifys.png')
                          : require('@/assets/project/modifys-h.png')
                    },
                    style: {
                      cursor: 'pointer',
                      'margin-right': '5px',
                      'vertical-align': 'middle',
                      display: 'inline-block',
                      marginBottom: '4px'
                    }
                  })
                ]
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    'ok-text': '确定',
                    'cancel-text': '取消',
                    type: 'error',
                    size: 'large',
                    title: '你确定要删除吗?',
                    transfer: true
                  },
                  on: {
                    'on-ok': () => {
                      this.delItem(params.row.id);
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'text',
                        size: 'small',
                        disabled:
                          (!this.isRootDesigner && params.row.creator != this.USER_ID) ||
                          params.row.collect
                      },
                      attrs: {
                        title: '删除'
                      },
                      style: {
                        background: 'none',
                        border: 'none',
                        boxShadow: 'none'
                      }
                    },
                    [
                      h('img', {
                        attrs: {
                          src: !(
                            (!this.isRootDesigner && params.row.creator != this.USER_ID) ||
                            params.row.collect
                          )
                            ? require('@/assets/project/delNote-h.png')
                            : require('@/assets/project/delNote-d.png')
                        },
                        style: {
                          cursor: 'pointer',
                          'margin-right': '5px',
                          'vertical-align': 'middle',
                          display: 'inline-block',
                          marginBottom: '4px'
                        }
                      })
                    ]
                  )
                ]
              )
            ]);
          }
        }
      ],
      columns: [
        {
            type: 'link',
            title: '技能树名称',
            key: 'name',
            placement: 'top-left',
            minWidth: 100,
            tooltip: true,
            on:{
              click: (data) => {
                this.$router.push({
                    name: 'skillTreeDetail',
                    query: {
                        name: data.name,
                        id: data.id
                    }
                });
              }
            }
        },
        {
            title: '可用状态', //0 否，1是
            key: 'available',
            minWidth: 50,
            placement: 'top-right',
            setColor: (available) => {
                return available ? 'var(--status-yes)' : 'var(--status-no)';
            },
            filter: (available) => {
                return handlerAvailable(available).txt;
            }
        },
        {
          title: '收藏人数', //0 否，1是
          key: 'collectCount',
          placement: 'top-right',
          minWidth:50,
          render: (h, params) => {
            return h(
              'Tag',
              {
                style: {
                  'text-align-last': 'justify',
                  cursor: 'pointer!important'
                },
                props: {
                  color: 'blue'
                },
                nativeOn: {
                  click: () => {
                    if (params.row.collectCount == 0) {
                      this.$Message.info('当前无人收藏该技能树');
                      return;
                    }
                    this.openCollectModal(params.row.id, params.row.name);
                  }
                }
              },
              params.row.collectCount
            );
          }
        },
        // {
        //     title:'检测结果',
        //     key:'checkResult',
        //     width:200,
        //     render:(h,params)=>{
        //         return h('Tooltip',{
        //             props:{
        //                 placement: 'top-start',
        //                 transfer: true,
        //                 maxWidth:200,
        //                 content:(!params.row.available)&&params.row.checkResult?params.row.checkResult:'-'
        //             },
        //             style:{
        //                 width:'100%'
        //             }
        //         },[
        //             h('span',{
        //                 style:{
        //                 'white-space': 'nowrap',
        //                 'text-overflow': 'ellipsis',
        //                 'overflow': 'hidden',
        //                 'width': '100%'
        //                 }
        //             },(!params.row.available)&&params.row.checkResult?params.row.checkResult:'-')
        //         ])
        //     }
        // },

        {
            title: '描述',
            key: 'description',
            ellipsis: true,
            tooltip: true,
            minWidth: 100
        },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'center',
          tooltip: true,
          width: 100,
          minWidth:50,
        },
        {
          title: '创建时间',
          key: 'createTime',
          minWidth:50,
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            placement: 'top-right',
            opList: [
                // {
                //     txt: '绑定角色',
                //     tooltip: (data) => {
                //         return !data.node;
                //     },
                //     title:
                //         '此技能树没有绑定技能，绑定角色后，技能树将无法创建或编辑节点内容，请确认是否开始绑定？',
                //     disabled: (data) => {
                //         return (
                //             (!this.isRootDesinger && data.creator != this.USER_ID) ||
                //             !data.available
                //         );
                //     },
                //     on:{
                //       click: (data,e) => {
                //           this.$router.push({
                //               name: 'SkillRoleUser',
                //               params: {
                //                   id: data.id
                //               }
                //           });
                //       }
                //     }
                // },
                {
                    txt: '启用',
                    tooltip: true,
                    title: '技能树所有节点间都创建了连线并且绑定了训练内容才可开启技能树,确认要启用此技能树？',
                    show: (data) => {
                        return !data.available;
                    },
                    setColor: () => {
                        return 'var(--status-yes)';
                    },
                    disabled: (data) => {
                        return (!this.isRootDesigner && data.creator != this.USER_ID) ||
                        data.collect;
                    },
                    on:{
                      click: (data,e) => {
                          let passObj = { ...data };
                          passObj.available = 1;
                          const txt = !data.available ? '启用' : '禁用';
                          modifySkill(passObj).then((res) => {
                              if (res.code == 1) {
                                  this.$Message.info(txt + '完成');
                                  this.queryList();
                              } else {
                                  this.$Message.error(res.message);
                              }
                          });
                      }
                    }
                },
                {
                    txt: '禁用',
                    tooltip: true,
                    title: '确认要禁用此技能树？',
                    show: (data) => {
                        return data.available;
                    },
                    setColor: () => {
                        return 'var(--status-no)';
                    },
                    disabled: (data) => {
                      return (!this.isRootDesigner && data.creator != this.USER_ID) ||
                      data.collect;
                    },
                    on:{
                      click: (data,e) => {
                        let passObj = { ...data };
                        passObj.available = 0;
                        const txt = data.currentVal ? '开启' : '关闭';
                        modifySkill(passObj).then((res) => {
                              if (res.code == 1) {
                                  this.$Message.info(txt + '完成');
                                  this.queryList();
                              } else {
                                  this.$Message.error(res.message);
                              }
                          });
                      }
                    }
                },
                {
                    txt: '预览',
                    on:{
                      click: (data,e) => {
                        this.showItem(data)
                      }
                    }
                },
                {
                    txt: '修改',
                    on:{
                      click: (data,e) => {
                          (this.modalTitle = '编辑技能树'), this.$refs.addmodal.open(data);
                      },
                    },
                    disabled: (data) => {
                      return (!this.isRootDesigner && data.creator != this.USER_ID)
                    }
                },
                {
                    txt: '删除',
                    tooltip: true,
                    type: 'delete',
                    title: '确定要删除吗？',
                    on:{
                      click: (data,e) => {
                        this.delItem(data.id);
                      },
                    },
                    disabled: (data) => {
                      return (!this.isRootDesigner && data.creator != this.USER_ID) ||
                      data.collect;
                    }
                }
            ]
        }
    ],
      datasource: [],
      total: 0,
      loading:false
    };
  },
  mounted() {
    // window.onresize = () => {
    //   this.resizeThrottle();
    // };
    // this.queryObj.pageSize = setDefaultHeight();
    this.queryList();
  },
  methods: {
    changeCollectPage(page) {
      this.collectSkillObj.pageIndex = page;
      this.getCollectSkillData();
    },
    getCollectSkillData(type) {
      getCollectSkillPeople(this.currentCollectId, this.collectSkillObj).then((res) => {
        if (res.code == 1) {
          const data = res.data.items;
          data.forEach((item) => {
            item.showName = item.nickName || item.userName;
          });
          this.collectSkillData = data;

          this.collectSkillTotal = res.data.total;
          if (type == 'openModel') {
            this.collectModal = true;
          }
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    openCollectModal(id, name) {
      this.currentCollectId = id;
      this.currentCollectSkill = name;
      this.collectSkillObj.pageIndex = 1;
      this.collectSkillObj.pageSize = 10;
      this.getCollectSkillData('openModel');
    },
    isCreatByMe() {
      this.queryObj.pageIndex = 1;
      this.queryList();
    },
    queryListD: debounce(function() {
      this.queryList();
    }, 500),
    resizeThrottle: throttle(function() {
      this.defaultPagesize = setDefaultHeight();
      this.queryObj.pageSize = this.defaultPagesize;
      this.queryList();
    }, 1000),
    addItem() {
      this.$refs.addmodal.open();
    },
    initQuery() {
      this.queryObj = {
        pageIndex: 1,
        pageSize: this.defaultPagesize,
        name: '',
        available: -1,
        isMe: false
      };
    },
    queryList(type) {
      this.loading = true;
      if (type == 'refresh') {
        this.initQuery();
      }
      const params = { ...this.queryObj };
      if (params.isMe) {
        params.creator = this.USER_ID;
      }
      delete params.isMe;
      if (params.available == -1) {
        delete params.available;
      }
      if (!params.name) {
        delete params.name;
      }
      querySkill(params).then((data) => {
        if (data.code === 1) {
          this.datasource = data.data.items;
          this.total = data.data.total;
        } else {
          this.$Message.error(data.message);
        }
        this.loading = false;
      }).catch(error => {
        this.loading = false;
      });
    },
    changePage(page) {
      this.queryObj.pageIndex = page;
      this.queryList();
    },
    changeSize(size) {
      this.queryObj.pageSize = size;
      this.queryList();
    },
    showItem(params) {
      this.$refs.treeDetail.open(params);
    },
    delItem(id) {
      delSkill(id).then((res) => {
        if (res.code == 1) {
          this.$Message.info('删除成功!');
          this.queryList();
        } else {
          this.$Message.error(res.message);
        }
      });
    }
  }
};
</script>
<style scoped src="./skill.css"></style>
